package com.sftz.modules.web.previewcert.service;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.nutz.dao.Cnd;
import org.nutz.dao.SqlManager;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Encoding;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.sftz.assets.entities.cret.CertCourseCertificateEntity;
import com.sftz.framework.util.QrCodeUtil;
import com.uxuexi.core.common.util.MapUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;

/**
 * @author   王宏伟
 * @Date	 2019年2月25日 	 
 */
@IocBean
public class PreviewCertViewService {

	@Inject
	private IDbDao dbDao;
	@Inject
	private SqlManager sqlManager;
	@Inject
	private PropertiesProxy dbConfig;

	private final static String COURESHONORCERT = "课程荣誉证书.pdf";
	//二维码图片大小
	private final static Integer QRCODEPICTURESIZE = 500;
	//DPI
	private final static Integer DPILENGTH = 100;
	private final static Integer DPIHEIGHT = 100;
	//边界宽度
	private final static Integer BORDERWIDTH = 200;
	//图片大小
	private final static Integer SCALEABSOLUTELENGTH = 110;
	private final static Integer SCALEABSOLUTEHEIGHT = 110;
	//图片大小
	private final static Integer ABSOLUTEPOSITIONLENGTH = 70;
	private final static Integer ABSOLUTEPOSITIONHEIGHT = 105;

	private final static String URL = "/modules/web/previewcert/previewCertFile.html?number=";
	private final static String TIPS = "您访问的证书不存在！";

	/**
	 * wx预览课程证书
	 * @author	王宏伟
	 * @Date	2019年2月25日
	 */
	public Object verify(String number, HttpServletResponse response) {
		CertCourseCertificateEntity courseHonorCert = dbDao.fetch(CertCourseCertificateEntity.class,
				Cnd.where("certificateNumber", "=", number));
		if (!Util.isEmpty(courseHonorCert)) {
			//模板路径
			URL url = getClass().getClassLoader().getResource(COURESHONORCERT);
			String templatePath = url.getPath();
			//生成临时路径
			String tmpdir = System.getProperty("java.io.tmpdir");
			File dir = new File(tmpdir);
			if (!dir.exists()) {
				dir.mkdir();
			}

			String nickname = courseHonorCert.getNickname();
			String courseName = courseHonorCert.getCourseName();
			String fileName = nickname + "_" + courseName + ".pdf";

			String newPDFPath = tmpdir;
			if (newPDFPath.endsWith(File.separator)) {
				newPDFPath = tmpdir + fileName;
			} else {
				newPDFPath = tmpdir + File.separator + fileName;
			}

			PdfReader reader;
			FileOutputStream out;
			ByteArrayOutputStream bos;
			PdfStamper stamper;
			try {
				//输出流
				out = new FileOutputStream(newPDFPath);
				//读取pdf模板
				reader = new PdfReader(templatePath);
				bos = new ByteArrayOutputStream();
				stamper = new PdfStamper(reader, bos);
				AcroFields s = stamper.getAcroFields();

				Map<String, Object> transBean2Map = transBean2Map(courseHonorCert);
				String courseNameString = courseHonorCert.getCourseName();
				int courseNameLength = courseNameString.length();
				boolean sign = true;
				//课程最大行数
				int rowNumber = 12;
				int MaxNumber = 20;
				if (courseNameLength <= rowNumber) {//一行
					sign = true;
				} else if (courseNameLength > rowNumber && courseNameLength <= MaxNumber) {
					sign = false;
				}

				Iterator<String> iterator = s.getFields().keySet().iterator();
				while (iterator.hasNext()) {
					String name = iterator.next().toString();

					if (("nickname").equals(name)) {
						String value = transBean2Map.get(name).toString();
						s.setField(name, value);
						continue;
					}
					if (("courseName").equals(name) || ("courseName1").equals(name) || ("courseName2").equals(name)) {

						if (sign) {
							if (("courseName").equals(name)) {
								String value = transBean2Map.get(name).toString();
								s.setField(name, value);
								continue;
							}
						} else {
							String nameString = "courseName";
							if (("courseName1").equals(name)) {
								String value = transBean2Map.get(nameString).toString();
								int result = value.length() / 2;
								String substring1 = substring(value, 0, result);
								s.setField(name, substring1);
								continue;
							}
							if (("courseName2").equals(name)) {
								String value = transBean2Map.get(nameString).toString();
								int result = value.length() / 2;
								String substring2 = substring(value, result, courseNameLength);
								s.setField(name, substring2);
								continue;
							}
							continue;
						}
					}
					if (("certificateNumber").equals(name)) {
						String value = transBean2Map.get(name).toString();
						s.setField(name, value);
						continue;
					}
					if (("issueTime").equals(name)) {
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						String value = format.format(courseHonorCert.getIssueTime());
						s.setField(name, value);
						continue;
					}
				}

				String signatureNonce = UUID.randomUUID().toString();
				String qrCodePath = tmpdir + File.separator + signatureNonce + ".jpg";
				String certUrl = dbConfig.get("weapp_domain") + URL + courseHonorCert.getCertificateNumber();

				boolean createQrCode = QrCodeUtil.createQrCode(new FileOutputStream(new File(qrCodePath)), certUrl,
						QRCODEPICTURESIZE, "JPEG");
				if (createQrCode) {
					Document document = new Document();
					document.open();
					Image gif = Image.getInstance(qrCodePath);
					gif.setDpi(DPILENGTH, DPIHEIGHT);
					gif.setBorderWidth(BORDERWIDTH);
					gif.scaleAbsolute(SCALEABSOLUTELENGTH, SCALEABSOLUTEHEIGHT); //图片大小：长度，高度
					gif.setAbsolutePosition(ABSOLUTEPOSITIONLENGTH, ABSOLUTEPOSITIONHEIGHT); //图片位置： 长度，高度
					PdfContentByte over = stamper.getOverContent(1);
					over.addImage(gif);
				}

				//如果为false那么生成的PDF文件还能编辑，一定要设为true
				stamper.setFormFlattening(true);
				stamper.close();

				Document doc = new Document();
				PdfCopy copy = new PdfCopy(doc, out);
				doc.open();
				PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
				copy.addPage(importPage);
				doc.close();

				String filename = URLEncoder.encode(fileName, Encoding.UTF8);
				response.setContentType("application/pdf;charset=utf8");
				response.setHeader("Content-Disposition", "inline; filename=\"" + filename + "\"");
				File newFile = new File(newPDFPath);
				InputStream is = new FileInputStream(newFile);
				return is;
			} catch (Exception e) {
				e.printStackTrace();
				return TIPS;
			}
		} else {
			//证书信息不存在
			return TIPS;
		}

	}

	/**
	 * dto转map
	 */
	public Map<String, Object> transBean2Map(Object obj) {
		if (obj == null) {
			return null;
		}
		Map<String, Object> map = MapUtil.map();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				// 过滤class属性  
				if (!"class".equals(key)) {
					// 得到property对应的getter方法  
					Method getter = property.getReadMethod();
					Object value = getter.invoke(obj);
					map.put(key, value);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 分割字符串，如果开始位置大于字符串长度，返回空
	 * (原始字符串，开始位置,结束位置)
	 * @author	王宏伟
	 * @Date	2019年2月26日
	 */
	public static String substring(String str, int start, int end) {
		if (start > str.length())
			return null;
		if (end > str.length()) {
			return str.substring(start, str.length());
		} else {
			return str.substring(start, end);
		}
	}
}
